﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

using SharedGenomics.Core;
using SharedGenomics.Domain;

namespace SharedGenomics.Workbench.PresentationModel
{
    public class AnalysisResultDataColumnSchema : DataColumnSchema
    {
        public AnalysisResultDataColumnSchema(Type resultType)
        {
            resultType.ThrowIfNull("resultType");
            ExceptionHelper.ThrowIf<ArgumentException>(!typeof(AnalysisResult).IsAssignableFrom(resultType), "Result type must be an AnalysisResult");

            this.ResultType = resultType;
            this.SnpProperties = (from pi in resultType.GetProperties()
                                  let snpAtts = pi.GetCustomAttributes(typeof(SnpAttribute), true)
                                  where snpAtts.Length > 0
                                  select pi).ToDictionary(p => p.Name);

            this.SnpPropertyIndicies = new Dictionary<int, string>();
        }

        public override void Add(DataGridColumnInfo column)
        {
 	        base.Add(column);

            //if the bound property is has a snp attribute (i.e. is in the SnpProperties dictionary) then add the column index to the indicies dictionary
            if (this.SnpProperties.ContainsKey(column.PropertyName))
            {
                this.SnpPropertyIndicies[column.Index] = column.PropertyName;
            }
        }

        public virtual IEnumerable<KeyValuePair<int, PropertyInfo>> GetResultSnpProperties()
        {
            return this.SnpPropertyIndicies.Select(kvp => new KeyValuePair<int, PropertyInfo>(kvp.Key, this.SnpProperties[kvp.Value]));
        }

        public bool IsSnpColumn(int index)
        {
            var column = this[index];
            return this.SnpProperties.ContainsKey(column.PropertyName);
        }

        public Type ResultType { get; private set; }
        private IDictionary<int, string> SnpPropertyIndicies { get; set; }
        private IDictionary<string, PropertyInfo> SnpProperties { get; set; }
    }
}
